/* $Id: Thumbnails.java,v 1.2 1999/03/17 02:21:36 duncan Exp $
 *
 */

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ResourceBundle;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.sql.*;

/**
 * A Servlet to help view jpg images
 *
 * @author James Chy
 */
 
public class ThumbSrvlt extends HttpServlet {

    String title, imgStrPath, thbStrPath;
    int newThumbs, updatedThumbs;
    double maxSize;
    ResourceBundle rb;
    boolean showQuery;
    PrintWriter out;
    String connection;

    static final long serialVersionUID = 0;
    
    public void init(ServletConfig config) throws ServletException
    {
        super.init(config);
        rb = ResourceBundle.getBundle("LocalStrings");
        title = rb.getString("servletAlbum.title");
        showQuery = rb.getString("servletAlbum.showQuery").equals("yes");
        imgStrPath = rb.getString("servletAlbum.start");
        thbStrPath = rb.getString("servletAlbum.thumbs");
        maxSize = Double.parseDouble(rb.getString("servletAlbum.thumbsize"));
        connection = rb.getString("servletAlbum.connection");
    }
        

    public ResultSet executeQuery(String query)
    {
        ResultSet rs=null;
        try
        {
            Class.forName("org.gjt.mm.mysql.Driver").newInstance();
            java.sql.Connection conn;
            conn = DriverManager.getConnection(connection);
//                   "jdbc:mysql://localhost/test?user=jimchy&password=lavacat1");
            Statement stmt;

            stmt=conn.createStatement();
            // if(showQuery) out.println("Query: " + query + "<BR>");
                  
            rs = stmt.executeQuery(query);

        }
        catch(ClassNotFoundException cnfe)
        {
            out.println("Class Not Found Exception "+cnfe.toString());
        }
        
        catch(InstantiationException ie)
        {
            out.println("Instantiation Exception "+ie.toString());
        }        
        catch(IllegalAccessException iae)
        {
            out.println("Illegal Access Exception "+iae.toString());
        }
        catch(SQLException sqle)
        {
            out.println("SQL Exception "+sqle.toString());
        }

        return rs;
    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");
        out = response.getWriter();

        int newThumbs = 0;
        int updatedThumbs = 0;

        out.println("<html>");
        out.println("<body bgcolor=\"white\">");
        out.println("<head>");

		out.println("<title>" + title + "</title>");  
        out.println("</head>");
        out.println("<body>");

		// note that all links are created to be relative. this
		// ensures that we can move the web application that this
		// servlet belongs to to a different place in the url
		// tree and not have any harmful side effects.

           
        if(showQuery) out.println("ImgStrPath: " + imgStrPath + "<BR>");

        File imgFilePath = new File(imgStrPath);

        if(showQuery) out.println("Directory: " + imgFilePath.isDirectory() +
                                  " Exists: " + imgFilePath.exists() + "<BR>");
            
        String[] images = imgFilePath.list();
           
        if(showQuery)  out.println("images.length = " + images.length + "<BR>");

        content_block:
        for( int i = 0; i < images.length; i++)
        {
            if(!images[i].endsWith(".jpg") && !images[i].endsWith(".JPG") ) 
               continue content_block;

            String imgStr = imgStrPath + "\\" + images[i];
            String thbStr = thbStrPath + "\\" + images[i];

            File imgFile = new File(imgStr);
            File thbFile = new File(thbStr);
    
            if(showQuery)  out.println("images[" + i + "] = " + images[i] + "<BR>");

            if( ( imgFile.exists() && !thbFile.exists() )
              || ( imgFile.exists() && thbFile.exists() &&
               thbFile.lastModified() < imgFile.lastModified() ) )
            {

                if(thbFile.exists()) updatedThumbs++;
                else newThumbs++;

                try
                {
                    double scale;            
                    int thumbWidth, thumbHeight;
    
                    BufferedImage bufi = ImageIO.read(imgFile);
                    BufferedImage thumbnailImage = null;
                
                    if(bufi.getWidth() > bufi.getHeight())
                    {
                        scale=maxSize/bufi.getWidth();
                        thumbWidth=(int)maxSize;
                        thumbHeight=(int)(maxSize * bufi.getHeight() / bufi.getWidth());
                    }
                    else
                    {
                        scale=maxSize/bufi.getHeight();
                        thumbWidth=(int)(maxSize * bufi.getWidth() / bufi.getHeight());
                        thumbHeight=(int)maxSize;
                    }
    
                    AffineTransform xform = AffineTransform.getScaleInstance(scale, scale);
                    AffineTransformOp op = new AffineTransformOp(xform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);            
    
                    thumbnailImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
                    Graphics2D g = thumbnailImage.createGraphics();
                    g.drawImage(bufi, op, 0, 0);
    
                    ImageIO.write(thumbnailImage, "jpeg", thbFile); 
                }
                catch(IOException ioe)
                {
                    out.println("I/O Exception");
                } // catch

                out.print("<A action=post href=\"OneImage?image=" + images[i] + "\">");
                out.print("<img src=\"/thumbs/" + images[i] + "\">");
                out.print("</A>");
                out.println("<BR>");

            } // if !thbFile exists or thbFile is newer than imgFile

        } // for i

        out.println("New Thumbnails: " + newThumbs + "<BR>");
        out.println("Updated Thumbnails: " + updatedThumbs + "<BR>");

        out.println("</body>");
        out.println("</html>");
    }
}



